package com.upload.jms.audited;

import com.upload.bean.web.FileUploadRequestBean;
import com.upload.bean.web.FileUploadResponseBean;
import com.upload.util.JSONUtil;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.ProducerCallback;
import org.springframework.stereotype.Component;

import javax.jms.*;
import java.util.UUID;

/**
 * Created by STARF on 2017/3/28.
 */
@Component
public class UploadToWebClient {

    private final static Logger LOG = LoggerFactory.getLogger(UploadToWebClient.class);

    private final static String QUEUE_NAME = "com.huanqiushuju.upload.audit";

    private FileUploadResponseBean result;

    @Autowired
    private JmsTemplate jmsTemplate;

    public FileUploadResponseBean sender(FileUploadRequestBean requestBean) throws JMSException {

        result = new FileUploadResponseBean();

        //设置消息接收超时时间5秒
        jmsTemplate.setReceiveTimeout(5000);

        Destination queue = new ActiveMQQueue(QUEUE_NAME);
        jmsTemplate.execute(queue, new ProducerCallback<Object>() {
            @Override
            public Object doInJms(Session session, MessageProducer messageProducer) throws JMSException {
                return null;
            }
        });

        Message message = jmsTemplate.sendAndReceive(queue, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {

                //新建一个结果返回通道，并监听这个通道
                Destination tempDest = session.createTemporaryQueue();

                //设置发送的消息的内容
                TextMessage textMessage = session.createTextMessage();
                textMessage.setText(requestBean.toString());
                textMessage.setJMSReplyTo(tempDest);

                String correlationId = String.valueOf(UUID.randomUUID());
                textMessage.setJMSCorrelationID(correlationId);

                LOG.info("client send.");
                return textMessage;
            }
        });

        //加上这个判断条件，如果server端出现异常，message为null
        if (message instanceof ActiveMQTextMessage) {
            ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;

            System.out.println(textMessage.getText());
            result = JSONUtil.toBean(textMessage.getText(), FileUploadResponseBean.class);
        }
        return result;
    }
}
